<?php
declare (strict_types = 1);

namespace app\controller\api;

use app\BaseController;
use app\helpers\ArrayHelper;
use app\helpers\DateFormatHelper;
use app\model\Orders;
use app\model\Shops;
use Carbon\Carbon;
use statistics\Dashboard;
use think\Db;
use think\helper\Arr;
use think\Request;

class DashboardController extends BaseController
{

    public function index(Request $request)
    {
        try {
            $successTotal = 0;
            $totalMoney = '0.00';
            $successRate = '0.00';
            $chartData = [];
            $this->validate($request->all(), ['shop_name' => 'require', 'order_date' => 'require']);
            $shop = Shops::query()->where('name', $request->get('shop_name'))->findOrEmpty();
            if ($shop->isEmpty()) throw new \Exception('shop not exists');
            $date = $request->param('order_date');

            return $this->getNdata($shop->id,$date);

            $dateBetween = [
                Carbon::parse(Arr::first($date))->timestamp,
                Carbon::parse(Arr::last($date))->timestamp,
            ];

            $list = Orders::query()
                ->where('shop_id', $shop->id)
                ->where('created_at', '>=',Arr::first($dateBetween))
                ->where('created_at', '<=',Arr::last($dateBetween))
                ->order('created_at','ASC')
                ->field([
                    'created_at',
                    'total_price',
                    'order_status',
                    'shop_id',
                ])
                ->select()
                ->toArray();
            if(empty($list))  return $this->success(compact('totalMoney','successTotal','successRate','chartData'));
            $orderStatusArr = ArrayHelper::arrayGroupByKey($list,'order_status');
            $totalCount = count($list);
            $successOrderArr = $orderStatusArr[Orders::ORDER_STATUS_COMPLETED] ?? [];
            $successTotal = count($successOrderArr);
            $successRate = $totalCount > 0 ? bcdiv(strval($successTotal),strval($totalCount),4) : '0.00';
            $successRate = bcmul(strval($successRate),'100',2);
            $totalMoney = array_sum(array_column($successOrderArr,'total_price'));
            $totalMoney = bcadd(strval($totalMoney),'0',2);
            $orderDateArr = ArrayHelper::arrayGroupByKey($successOrderArr,'created_at');
            //格式化输出数据图
            $chartData = $this->formatChartData($orderDateArr);
            return $this->success(compact('totalMoney','successTotal','successRate','chartData'));

        }catch (\Exception $e){
            //dump($e);
           throw new \Exception($e->getMessage());
        }



    }


    private function getNdata($shop_id,$date){

        $startD = date('Ymd',strtotime(Arr::first($date)));
        $startE = date('Ymd',strtotime(Arr::last($date)));

        $handel = new Dashboard($shop_id,$startD,$startE);
        return $this->success($handel->topSta());
    }

    protected function formatChartData($orderDateArr,$dateRange=[])
    {
        $list = [];
        if(empty($orderDateArr)) return $list;
        foreach ($orderDateArr as $date => $arr){
            $money = array_sum(array_column($arr,'total_price'));
            $money = bcadd(strval($money),'0',2);
            $list[] = [
                'date'=>$date,
                'value'=>$money
            ];
        }

        if($dateRange){
            $res = [];
            $dateRange = DateFormatHelper::getDateBetween(Arr::first($dateRange),Arr::last($dateRange));
            foreach ($dateRange as $date){
                foreach ($list as $index => $item){
                    $res[] = [
                        'date'=>$date,
                        'value'=>$item['date'] == $date ? $item['value'] : '0.00'
                    ];
                }
            }
            $list = $res;
        }

        return $list;

    }



}
